import { defineStore } from 'pinia'
import router from '@/router/index.js'

export const useMenuTabStore = defineStore('menuTab', {
  // 定义状态
  state: () => ({
      skLoading:true,
      activePath:"/dashboard",
      menuList:[{name: 'DashBoard',path: '/dashboard'}]
  }),

  // 定义动作
  actions: {
    // 点击改变菜单
    changeMenuTab(path){
      this.activePath = path
      router.push(path);
    },

    clear(){
      this.skLoading = false;
      this.menuList = []
    },

    // 添加菜单
    addMenuTab({name,path}){
      if(name && path){
        var index =  this.menuList.findIndex(m=>m.path==path);
        // 激活当前路径
        this.activePath = path
        if(index === -1){
          this.menuList.push({name,path})
        }
      }
    },
    // 移除
    removeMenuTab(path){
      var tabs = this.menuList;
      var activeTabPath = this.activePath;
      if(activeTabPath === path){
        tabs.forEach((tab,index)=>{
           if(tab.path == path){
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if(nextTab){
              activeTabPath = nextTab.path;
            }
           }
        })
      }  

      this.activePath = activeTabPath;
      var index =  this.menuList.findIndex(m=>m.path==path);
      // 开始删除
      this.menuList.splice(index,1)
      // 删除激活控制面板
      router.push(activeTabPath);
    }
  },
  persist: {
    key: 'mayan-pinia-skeleton',
    storage: localStorage,//sessionStorage
  }
})